﻿/// <reference path="jquery-1.4.1-vsdoc.js"/>

var user = null;
var now = new Date();
var m_names = ["January", "February", "March",
                    "April", "May", "June", "July", "August", "September",
                    "October", "November", "December"];

// this function is fired when the document is in the ready state.
function documentLoad() {

    $("#userProfile").tabs();
//    $("#divAvatar").dialog({
//        autoOpen: false,
//        closeOnEscape: true,
//        draggable: false,
//        height: 'auto',
//        width: 'auto',
//        title: 'Change Avatar',
//        modal: false,
//        resizable: false     
//    });
    /* Remove the X in the dialog box */
    //$('.ui-dialog-titlebar-close').remove();

    $("#divErrorMessages").hide();
    $("#divErrorMessages").accordion({ collapsible: true, autoHeight: false, header: "h3" });

    $("#btnAvatarCancel").click(function (e) {
        $("#divAvatar").dialog('close');
    });

    $("#btnPassword").button().click(function () {
        $("<div><iframe src='/Account/ChangePassword' width='330px' height='300px'></iframe></div>").dialog({
            autoOpen: true,
            closeOnEscape: true,
            draggable: false,
            height: 'auto',
            width: 'auto',
            title: 'Change Password',
            modal: false,
            resizable: false
        });
    });
    $("#btnChangeAvatar").click(function () {
        $("#divAvatar").dialog('open');
    });

    
    $("#Save").click(function () {
        SaveUserDetails();
    });

    $("#Cancel").click(function () {
        Close();
    });

    /* Add the date picker to the date of birth field */
    $("#txtDateOfBirth").datepicker({ onSelect: function (date) { },
        dateFormat: "MM dd, yy",
        yearRange: (now.getYear()-80) + ":" + now.getYear(),
        showOn: "both", 
        changeMonth: true, changeYear: true
    });

    /* Disable direct entry into the textbox */
    $("#txtDateOfBirth").attr('readonly', true);
    $('#ui-datepicker-div').css('z-index', 2005);

    /* attach event handler to the selected event */
    $("#drpCountry").change(function () {
        LookupStates();
    });

    /* Load User Information */
    var userGUID = { "userGuidAsString": $("#txtUserId").val() };
    CallWebService(accountsGetUserUrl, userGUID, function (result) {
        ShowUserDetails(result);
    });

    /* Upload control */
    var button = $('#txtAvatarBrowse'), interval;
    var upload = new AjaxUpload(button, {
        action: fileUploadUrl,
        name: 'avatar',
        onSubmit: function (file, ext) {
            //checking file extension
            if (!(ext && /^(jpg|png|jpeg|gif)$/.test(ext))) {
                // extension is not allowed
                alert('Error: invalid file extension');
                // cancel upload
                return false;
            }

            // change button text, when user selects file			
            button.text('Uploading');
            // provide the userguid as a querystring
            this.setData({ 'UserGuid': $("#txtUserId").val() });

            // If you want to allow uploading only 1 file at time,
            // you can disable upload button
            this.disable();

            // Uploading -> Uploading. -> Uploading..
            interval = window.setInterval(function () {
                var text = button.text();
                if (text.length < 13) {
                    button.text(text + '.');
                } else {
                    button.text('Uploading');
                }
            }, 200);
        },
        onComplete: function (file, response) {
            button.text('Upload');
            /*
            //checking file extension
            if (!(ext && /^(jpg|png|jpeg|gif)$/.test(ext))) {
            // extension is not allowed
            window.clearInterval(interval);
            this.enable();
            alert('Error: invalid file extension');
            // cancel upload
            return false;
            }
            */
            window.clearInterval(interval);

            // enable upload button
            this.enable();
            // add file to the picturebox
            var extension = (file.substr(file.indexOf(".") + 1, file.length - file.indexOf(".") - 1));
            $("#divAvatar").dialog('close');
            window.location.reload(true);
        }
    });

    // add preset images
    $("#imgPerson1").attr("src", preSetImagesUrl + "Person1.png");
    $("#imgPerson2").attr("src", preSetImagesUrl + "Person2.png");
    $("#imgPerson3").attr("src", preSetImagesUrl + "Person3.png");
    $("#imgPerson4").attr("src", preSetImagesUrl + "Person4.png");

    //wire up mouseovers for images
    $(".avatarImages").click(function (e) {
        //$('#picAvatar').attr("src", $(e.currentTarget)[0].src);
        var input = { "userGuid": $("#txtUserId").val(), "layout": $(e.currentTarget)[0].src };
        CallWebService(accountsSavePresetAvatarUrl, input, function (result) {
            window.location.reload(true);
            var response = JSON.parse(result.d);
            if (response.IsSuccess == false) {
                ShowErrorMessage(response);
            }
        });
        $("#divAvatar").dialog('close');
    });

    $(".avatarImages").mouseenter(function (e) {
        $(e.currentTarget).addClass("avatarImages-Highlighted");
    });

    $(".avatarImages").mouseleave(function (e) {
        $(e.currentTarget).removeClass("avatarImages-Highlighted");
    });
    $("#picAvatar").attr("src", GetPicProfileUrl("100", "100"));
}

function Close() {
    window.location.href = "/";
}

function LookUpCountries() {
    // clear the dropdowns
    $("#drpCountry").empty();
    CallWebService(lookupCountriesUrl, "",
        function (result) {
            var response = JSON.parse(result.d);
            if (response.IsSuccess == true) {
                var countries = response.Payload;
                for (var i = 0; i < countries.length; i++) {
                    $('#drpCountry').append("<option value='" + countries[i].ID + "'>" + countries[i].Name + "</option>")
                }
                $("#drpCountry").val(user.Info.Country);
                LookupStates();
            }
        });        
}

function LookupStates() {
    $("#drpState").empty();
    var countryId = { "countryId": $("#drpCountry").val() };
    CallWebService(lookupStatesUrl, countryId,
                    function (result) {
                        var response = JSON.parse(result.d);
                        if (response.IsSuccess == true) {
                            var states = response.Payload;
                            for (var i = 0; i < states.length; i++) {
                                $('#drpState').append("<option value='" + states[i].ID + "'>" + states[i].Name + "</option>")
                            }
                            $("#drpState").val(user.Info.State);
                        }
                    });
}

/* Validate entered field on the form, returns false for validation errors */
function ValidateUserDetails() {
    var ret = false;
    var errors = new Array();
    if ($.trim($("#txtUsername").val()) == "") {
        errors[errors.length] = { "Control": "txtUsername", "Message": "Username cannot be empty." };
    }
    if ($.trim($("#txtFirstname").val()) == "") {
        errors[errors.length] = { "Control": "txtFirstname", "Message": "First name cannot be empty." };
    }
    if ($.trim($("#txtLastname").val()) == "") {
        errors[errors.length] = { "Control": "txtLastname", "Message": "Last name cannot be empty." };
    }
    if ($.trim($("#txtEmail").val()) == "") {
        errors[errors.length] = { "Control": "txtEmail", "Message": "Email cannot be empty." };
    }

    var errorHTML = "";
    if (errors.length > 0) {
        errorHTML = "<table>";
    }
    $.each(errors, function () {
        errorHTML += "<tr>";
        errorHTML += "<td controlId='" + this.Control + "' onclick=$('#" + this.Control + "').focus()>" 
                    + this.Message + "</td>";
        errorHTML += "</tr>";
    });
    if (errors.length > 0) {
        $("#divErrorMessages").show();
        errorHTML += "</table>";
        ret = false;
    }
    else {
        ret = true;
        $("#divErrorMessages").hide();
    }
    $("#divErrors").html(errorHTML);
    return ret;
}

function SaveUserDetails() {
    if (ValidateUserDetails() == true) {
        
        var user = {
            "basicInfo": { "Id": $("#txtUserId").val(),
                "Firstname": $("#txtFirstname").val(),
                "Lastname": $("#txtLastname").val(),
                "Email": $("#txtEmail").val()
            },
            "personalInfo": {
                "Nickname": $("#txtNickname").val(),
                "Sex": $("#drpSex").val(),
                "Mobile": $("#txtMobile").val(),
                "DateOfBirth": $("#txtDateOfBirth")[0].value,
               /* "AvatarUrl": htmlEncode($("#picAvatar").attr("src")), */ 
                "Phone": $("#txtPhone").val(),
                "State": $("#drpState").val(),
                "Country": $("#drpCountry").val(),
                "Postcode": $("#txtPostcode").val(),
                "Comment": $("#txtNotes").val()
            },
            "mailSettings": {
                "AcceptAdvertisingEmail": eval($("#chkAdvertisingEmail").is(":checked")),
                "AcceptCommunityEmail": eval($("#chkCommunityEmail").is(":checked"))
            }
        };
        var userObj = "user=" + JSON.stringify(user);
        CallWebService(accountsSaveUserUrl, userObj,
            function (result) {
                var response = JSON.parse(result.d);
                if (response.IsSuccess == false) {
                    ShowErrorMessage(response);
                } else {
                    //reload data
                    var userGUID = { "userGuidAsString": $("#txtUserId").val() };
                    CallWebService(accountsGetUserUrl, userGUID, function (result) {
                        ShowUserDetails(result);
                    });
                }
            });
            alert("Saved successfully.");        
    }
}

function ShowUserDetails(result) {
    var response = JSON.parse(result.d);
    if (response.IsSuccess == true) {
        user = response.Payload;
        /* Personal Details */
        $("#txtUsername").attr("value", user.User.UserName);
//        $("#picAvatar").attr("src", GetPicProfileUrl("100", "100"));
        $("#txtFirstname").attr("value", user.Info.Firstname);
        $("#txtLastname").attr("value", user.Info.Lastname);
        $("#txtNickname").attr("value", user.Info.Nickname);
        $("#txtEmail").attr("value", user.User.Email);
        $("#txtLastActivityDate").attr("value", user.User.LastActivityDate);
        $("#txtDateCreated").attr("value", user.User.CreationDate);
        if (user.Info.DateOfBirth != "") {
            var dob = new Date(user.Info.DateOfBirth);
            $("#txtDateOfBirth")[0].value = m_names[dob.getMonth()] + " " + dob.getDate() + ", " + dob.getFullYear();
        }
        $("#drpSex").val(user.Info.Sex);
        $("#txtPhone").attr("value", user.Info.Phone);
        $("#txtMobile").attr("value", user.Info.Mobile);

        /* Mailing Preferences */
        $("#chkCommunityEmail").attr("checked", user.Pref.AcceptCommunityEmail);
        $("#chkAdvertisingEmail").attr("checked", user.Pref.AcceptAdvertisingEmail);

        /* Contact Details */
        $("#txtPostcode").attr("value", user.Info.Postcode);
        LookUpCountries();

        /* Other */
        $("#txtNotes")[0].innerText = user.Info.Comment;
    }
    else {
        ShowErrorMessage(response);
    }
    return;
}